using System;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using FlickrNet;

namespace FlickrControls
{
    /// <summary>
    /// Interaction logic for FlickrViewer.xaml
    /// </summary>

    public partial class FlickrViewer :  LoungrCore.ILoungrModule
    {
        Flickr flickr;
        private BitmapImage bmp;

        public FlickrViewer()
        {
            InitializeComponent();

            //BitmapImage bmp = new BitmapImage(new Uri(@"C:\Temp\20070421084.jpg"));
            //MainImage.Source = bmp;

            //MainImage.Stretch = Stretch.Uniform;
        }

        void bmp_DownloadCompleted(object sender, EventArgs e)
        {
            MainImage.Source = bmp;
        }


        #region ILoungrModule Members

        public void ChangeItem()
        {
            

            //MainImage.Dispatcher.

            bool access = MainImage.CheckAccess();
            if (access)
            {
                SetImage();
            }
            else
            {
                SetImageDelegate sid = SetImage;
                MainImage.Dispatcher.BeginInvoke(DispatcherPriority.Normal, sid);
            }
            //MainImage.Source = bmp;
            
        }

        private delegate void SetImageDelegate();

        private bool first = true;

        public void SetImage()
        {
            PhotoSearchOptions options = new PhotoSearchOptions();
            options.Tags = "kayak";
            Photos returnedPhotos = flickr.PhotosSearch(options);

            Random r = new Random();
            int index = r.Next(0, 9);

            bmp = new BitmapImage(new Uri(returnedPhotos.PhotoCollection[index].MediumUrl));

            //if (first)
            //{
            //    bmp.DownloadCompleted += new EventHandler(bmp_DownloadCompleted);
            //    first = !first;
            //}
            
            
            MainImage.Source = bmp;
        }

        public void Intialise()
        {
            flickr = new Flickr("340980081028bac5fe3e845a1a3b7a60");
        }

        #endregion
    }
}